﻿using aztall.Module.BusinessObjects;
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.PivotGrid.Win;
using DevExpress.Utils;
using DevExpress.XtraPivotGrid;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aztall.Module.Win.Controllers
{
	public static class PivotGridHelper
	{
		public static ConfigValue AddView(XafPivotGridControl pivotGrid, IObjectSpace ios, ConfigGroup configGroup, string configName, string viewName)
		{
			Config config = ios.FindObject<Config>(CriteriaOperator.Parse("ConfigGroup = ? and ConfigName = ?", configGroup, configName));
			if (config == null)
			{
				config = ios.CreateObject<Config>();
				config.ConfigGroup = configGroup;
				config.ConfigName = configName;
			}
			ConfigValue result = config.Values.Where(c => c.Value.ToUpper() == viewName.ToUpper()).FirstOrDefault();
			if (result == null)
			{
				result = ios.CreateObject<ConfigValue>();
				result.Role = null;		// all roles
				result.User = null;		// all users
				config.Values.Add(result);
			}
			result.Value = viewName;

			MemoryStream ms = new MemoryStream();
			pivotGrid.SaveLayoutToStream(ms,DevExpress.Utils.OptionsLayoutBase.FullLayout);
			ms.Position = 0;
			var sr = new StreamReader(ms);
			result.Tag = sr.ReadToEnd();
			sr.Close();
			ms.Close();
			ios.CommitChanges();

			return result;
		}
		public static void SetView(XafPivotGridControl pivotGrid, ConfigValue configValue)
		{
			using (MemoryStream ms = new MemoryStream())
			{
				using (StreamWriter sw = new StreamWriter(ms))
				{
					sw.AutoFlush = true;
					sw.Write(configValue.Tag);
					ms.Position = 0;
					pivotGrid.RestoreLayoutFromStream(ms, DevExpress.Utils.OptionsLayoutBase.FullLayout);
					sw.Close();
				}
				ms.Close();
			}
		}
		public static void DeleteView(IObjectSpace ios, ConfigValue configValue)
		{
			configValue = ios.FindObject<ConfigValue>(new BinaryOperator("Oid", configValue.Oid));
			ios.Delete(configValue);
			ios.CommitChanges();
		}
	}
	public class PivotFieldItem
	{
		public string FieldCaption { get; set; }
		public string FieldName { get; set; }
		public PivotArea Area { get; set; }
		public FormatType FormatType { get; set; }
		public string FormatString { get; set; }
		public PivotGroupInterval GroupInterval { get; set; }
	}
}
